from datetime import *
from ordereddict import OrderedDict
gmt = ' +0200'
nu = datetime.now()
nu = nu.strftime("%a, %d %b %Y %H:%M:%S" + gmt)

# combining two lists into a dict comes in handy when dealing with database rows
def combineListsToDict(listA, listB):
    combinedList = zip(listA,listB)
    combinedDict = OrderedDict(combinedList)
    return combinedDict

### ----- generic page stuff

# page head (with <head> and dynamic title

def header(pagetitle):
    header ="""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head> 
    <link rel="shortcut icon" href="/static/images/favicon.ico" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <title>%s</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
    <script src="/static/js/ajax.js" type="text/javascript"></script>
    <script src="/static/js/highcharts.js" type="text/javascript"></script>
    <!-- <script type="text/javascript" src="static/js/themes/gray.js"></script> -->
    <script type="text/javascript" src="static/js/modules/exporting.js"></script>
    <link href='http://fonts.googleapis.com/css?family=EB+Garamond' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="/static/css/style.css" type="text/css"></link>
    <!-- to display math -->
    <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
    </script>
""" % (pagetitle)
    return header

# end of header, start of page (needs to be separate to push scripts in <head>
content = """
</head>
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
"""

# menu html
menu ="""
<h2> menu</h2>
"""
# main text function

def maintext():
    with open('text/fressen.html') as maintext:
        maintext = maintext.read()
        return maintext

# footer html
footer = """
<div class="clear"></div>
</div>
<div class="footer">
<br style="clear:both" /><sub>%s</sub>
</div>
</body>
</html>
""" % nu


### ----- content specific html

# population pyramid html & javascript
def standalone(tabletypes, deftabletype, E0values, defE0, sex, femratio, cohort):
    form ="""
    <form name="mltform" action="/mlt/" method="get">
<em>Ratio of females (percentage): &nbsp;</em><input type="text" name="femratio" value="%s" onFocus="if (this.value == %s) { this.value = ''; }">%%<br />
<em>Birth cohort size (absolute integer): &nbsp;</em><input type="text" name="cohort" value="%s" onFocus="if (this.value == %s) { this.value = ''; }"> <br />
""" % (femratio,femratio,cohort,cohort)
    formend='</form>'
    submit = '<input type="submit">'
    selectend= '</select><br />\n'
    ttselect = '<em>Type of MLT: &nbsp;</em><select name="tabletype">\n' 
    ttoptions = '<option value="%s" selected>%s</option>\n'% (deftabletype, deftabletype)
    e0select = '<em>Average life expectancy at <b>birth</b>: &nbsp;</em><select name="E0">\n' 
    e0options = '<option value="%s" selected>%s</option>\n'% (defE0, defE0)
    sexes = ['Male', 'Female']
    for tt in tabletypes:
        if tt != deftabletype:
            ttoptions += '<option value="%s">%s</option>\n'% (tt,tt)
    for e0 in E0values:
        if e0 != defE0:
            e0options += '<option value="%s">%s</option>\n'% (e0,e0)
    for sexe in sexes:
        if sex == 'Male':
            sexradio = '<em>Type of table:  &nbsp;</em> <input type="radio" name="sex" value="%s" checked>%s</input>\n<input type="radio" name="sex" value="%s">%s</input>'% (sexes[0], sexes[0], sexes[1],sexes[1])
        else:
            sexradio = '<em>Type of table:  &nbsp;</em><input type="radio" name="sex" value="%s" checked>%s</input>\n<input type="radio" name="sex" value="%s">%s</input>'% (sexes[1], sexes[1], sexes[0],sexes[0])

    return form + ttselect + ttoptions + selectend + e0select + e0options + selectend + sexradio + submit + formend
def pyramidcontainer(uniqid):
    return """ 
<div id="pyramid%s" width="700px" style="float: left;" height="400px"></div>
""" % (uniqid)
# highchart pyramid template

def pyramidtable(categories, femdata, maledata):
    female = ''
    male = ''
    cdfemale = combineListsToDict(categories, femdata)
    cdmale = combineListsToDict(categories, maledata)
    #cd = sorted(cd, key=cd.get, reverse=True)
    #sorted(cd.iteritems(), key=itemgetter(1), reverse=True)
    for k,v in cdfemale.items():
        female = female + "<tr><td>%s</td><td>%s</td></tr>\n" % (str(k),str(v))
    for k,v in cdmale.items():
        male = male + "<tr><td>%s</td><td>%s</td></tr>\n" % (str(k),str(abs(v)))
    femaletable = '<table class="femaletable pyramid"><tbody><tr><td class="age">Age</td><td>Female cohort size</td></tr>\n%s</tbody></table>' % female 
    maletable = '<table class="maletable pyramid"><tbody><tr><td class="age">Age</td><td>Male cohort size</td></tr>\n%s</tbody></table>' % male 
    table = '%s %s %s %s %s' % ('<div class="pyramidtable">', str(maletable),str(femaletable),'</div>', '<div class="clear"></div>')
    return table 

def pyramid(categories, tabledescription, cohortsize, femdata, maledata, uniqid):
    chart ="""
<script type="text/javascript">
                
var chart,
        categories = %s ;
$(document).ready(function() {
        chart = new Highcharts.Chart({
                chart: {
                        renderTo: 'pyramid%s',
                        defaultSeriesType: 'bar'
                },
                title: {
                        text: '%s'
                },
                subtitle: {
                        text: 'Source: http://esa.un.org/unpd/wpp/'
                },
                xAxis: [{
                        categories: categories,
                        reversed: false
                }, { // mirror axis on right side
                        opposite: true,
                        reversed: false,
                        categories: categories,
                        linkedTo: 0
                }],
                yAxis: {
                        title: {
                                text: null
                        },
                        labels: {
                                formatter: function(){
                                        return (Math.abs(this.value) / 1); 
                                }
                        },
                        min: -%s,
                        max: %s
                },
                
                plotOptions: {
                        series: {
                                stacking: 'normal'
                        }
                },
                
                tooltip: {
                        formatter: function(){
                                return '<b>'+ this.series.name +', age '+ this.point.category +'</b><br/>'+
                                         'Population: '+ Highcharts.numberFormat(Math.abs(this.point.y), 0);
                        }
                },
                
                series: [
                        
                        {name: 'Women',
                        data: %s},{
                        name: 'Men',
                        data: %s}
                        ]
        });
        
        
});
        
</script>

""" % (str(categories),uniqid,tabledescription,cohortsize,cohortsize,femdata, maledata)
    return chart
